package com.wsyu.springbootbackend.core.auth.handler;

import com.wsyu.springbootbackend.core.util.HttpServletUtils;
import com.wsyu.springbootbackend.core.util.JsonBuilder;
import com.wsyu.springbootbackend.core.util.JwtUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();

        String jwt = JwtUtils.create().addUsername(user.getUsername()).build();

        String jsonStr = JsonBuilder.create()
                .add("code", HttpStatus.OK.value())
                .add("msg", HttpStatus.OK.getReasonPhrase())
                .add("data", jwt)
                .build();

        HttpServletUtils.writeJsonResponse(response, HttpStatus.OK, jsonStr);
    }

}
